const express = require("express");
const cors = require("cors");
const app = express();
const userRouter = require("./router/user");

const expressJWT = require("express-jwt"); // 解析token
//配置跨域
app.use(cors());
//配置内置的解析post
app.use(express.json());
app.use(express.urlencoded());

//挂载路由
app.use("/api", userRouter);

//解析token
const { secretKey } = require("./config");
app.use(
  expressJWT({ secret: secretKey, algorithms: ["HS256"] }).unless({
    path: ["/", "/login", /^\/api$\//],
  })
);

const Joi = require("joi");
//错误级别中间件
app.use(function (err, req, res, next) {
  if (err.name == "UnauthorizedError") {
    return res.send({ msg: "token无效 身份认证失败" });
  }

  // 4.1 Joi 参数校验失败
  if (err instanceof Joi.ValidationError) {
    return res.send({
      status: 1,
      message: err.message,
    });
  }

  // 4.2 未知错误
  res.send({
    status: 1,
    message: err.message,
  });
});

app.listen(3000, () => {
  console.log("http://localhost:3000 running");
});
